<?php
/**
 * Free Web File Manager is free software released under MIT License.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
 * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 * George Sarafov
 * http://freewebfilemanager.com
 */

/** WordPress Administration Bootstrap */

require( dirname(__FILE__) . '/../wp-load.php' );
require( dirname(__FILE__) . '/transfer.php' );
global $wpdb;





/// 封装对数据库的操作
class GSFileSystemFileStorage {

    public $wpdb;

    public function __construct($wpdb){
        $this->wpdb=$wpdb;
    }
    public function is_dir($file) {
        return @is_dir($file);
    }

    public function file_exists($file) {
        return @file_exists($file);
    }
    /*
     *
     *
     查看 该id的文件或文件夹是否存在
	*/
    public function file_exists_2($id) {
        return $this->wpdb->query("SELECT *  FROM wp_catalogs WHERE id ='".$id."' and isValid='0'")  ;
    }
    /*
         *
         *
         查看 该id的文件或文件夹是否存在 并获取结果
        */
    public function file_exists_1($id) {
        return $this->wpdb->get_results("SELECT *  FROM wp_catalogs WHERE id ='".$id."'  and isValid='0'")  ;
    }
    /*
     *
     * ////查看当前目录下 该文件名的文件或文件夹是否存在
     */

    public function filename_exists($id,$filename) {

        return $this->wpdb->query("SELECT *  FROM wp_catalogs WHERE parentId ='".$id."' AND name='".$filename."'  and isValid='0'")  ;
    }

    public function scandir($id) {
        $querystr = "SELECT * FROM wp_catalogs WHERE parentId ='".$id."'  and isValid='0'  ORDER BY listOrder "  ;
        return  $this->wpdb->get_results($querystr);

    }

    public function filesize($file) {
        return @filesize($file);
    }

    public function deleteFile($file){
        return @unlink($file);
    }

    public function deleteDirectory($dirname){
        $files = scandir($dirname);
        if (count($files) > 2) {
            foreach( $files as $file ) {
                if ($file == '.' || $file == '..') {
                    continue;
                }
                if (is_dir($dirname.'/'.$file)) {
                    $this->deleteDirectory($dirname.'/'.$file);
                } else {
                    @unlink($dirname.'/'.$file);
                }
            }
        }
        return rmdir($dirname);
    }


    /*
     *
     * 根据 id he  filename 新建文件夹
     *
     */
    public function makeDirectory($id,$dirname){
        $result=  $this->wpdb->get_results("SELECT pathName FROM wp_catalogs WHERE id ='".$id."'  and isValid='0' " );

        $result1=  $this->wpdb->get_results("SELECT listOrder FROM wp_catalogs order by listOrder desc limit 0,1 " );
        $num=$result1[0]->listOrder+1;
        return $this->wpdb->query("INSERT INTO `wp_catalogs` ( `type`, `parentId`, `name`, `netAddr`, `fileAddr`, `pdfAddr`, `createTime`, `isValid`, `listOrder`,`display`, `pathName`) VALUES ( '2', '".$id."', '".$dirname."', NULL, NULL, NULL,now(), '0', '".$num."', '0', '".$result[0]->pathName."/".$dirname."')");
    }


    /*
     *
     * 根据 id he  filename 新建网址链接
     *
     */
    public function newLink($id,$dirname,$addr){
        $result1=  $this->wpdb->get_results("SELECT listOrder FROM wp_catalogs order by listOrder desc limit 0,1 " );
        $num=$result1[0]->listOrder+1;
        return $this->wpdb->query("INSERT INTO `wp_catalogs` ( `type`, `parentId`, `name`, `netAddr`, `fileAddr`, `pdfAddr`, `createTime`, `isValid`, `listOrder`,`display`, `pathName`) VALUES ( '0', '".$id."', '".$dirname."', '".$addr."', NULL, NULL, now(), '0', '".$num."', '0', NULL)");
    }

    /*
     *
     * 根据 id he  filename 修改网址链接
     *
     */
    public function changeLink($id,$dirname,$addr){
        return $this->wpdb->query("update  `wp_catalogs` set name='".$dirname."' , netAddr='".$addr."' where id='".$id."' ");

    }

    /*
         *
         * 根据 id he  filename 新建天气路线
         *
         */
    public function newWeatherPath($id,$source,$dest){
        $result1=  $this->wpdb->get_results("SELECT listOrder FROM wp_catalogs order by listOrder desc limit 0,1 " );
        $num=$result1[0]->listOrder+1;
        return $this->wpdb->query("INSERT INTO `wp_catalogs` ( `type`, `parentId`, `name`, `source`, `fileAddr`, `pdfAddr`, `createTime`, `isValid`, `listOrder`,`display`, `dest`) VALUES ( '3', '".$id."', '".$source."', '".$source."', NULL, NULL,now(), '0',  '".$num."', '0', '".$dest."')");
    }

    /*
     *
     * 根据 id he  filename 修改天气路线
     *
     */
    public function changeWeatherPath($id,$source,$dest){

        return $this->wpdb->query("update  `wp_catalogs` set name='".$source."' , source='".$source."' , dest = '".$dest."' where id='".$id."' ");
    }





    /*
     *
     * $result=  $this->wpdb->get_results("SELECT pathName FROM wp_catalogs WHERE id ='".$id."'  " );
            return $this->wpdb->query("INSERT INTO `wp_catalogs` ( `type`, `parentId`, `name`, `netAddr`, `fileAddr`, `pdfAddr`, `createTime`, `isValid`, `listOrder`,`display`, `pathName`) VALUES ( '2', '"
                .$id."', '".$dirname."', NULL, NULL, NULL, '".$time."', '0', '0','0','".$result[0]->pathName."//".$dirname."')");
     */

    /*


    /*
     *
     * 根据 id    filename 修改文件夹名称
     *
     */
    public function renameItemName($id,$name){

        return $this->wpdb->query("update  `wp_catalogs` set name='".$name."'  where id='".$id."' ");
    }

    /*
     *
     * 根据 id    删除文件夹名称
     *
     */
    public function deleteItem($id){

        return $this->wpdb->query("update  `wp_catalogs` set isValid='1'  where id='".$id."' ");
    }






    public function add_uploaded_file($id,$name,$filename,$pdfname){
        $result1=  $this->wpdb->get_results("SELECT listOrder FROM wp_catalogs order by listOrder desc limit 0,1 " );
        $num=$result1[0]->listOrder+1;
        $query="INSERT INTO `wp_catalogs` ( `type`, `parentId`, `name`, `fileAddr`, `pdfAddr`, `createTime`, `isValid`, `listOrder`,`display` ) VALUES ( '1', '".$id."', '".$name."', '".$filename."', '".$pdfname."',now(), '0', '".$num."', '0')";
        return  $this->wpdb->query($query);
    }


    /*
     *
     * 根据 id he  filename 修改天气路线
     *
     */
    public function changeDisplay($id,$display){

        return $this->wpdb->query("update  `wp_catalogs` set display='".$display."' where id='".$id."' ");
    }

    /*
     *
     * 修改某一条目位置
     */
    public function changeOrder($id,$upOrDown){

        $querystr = "SELECT * FROM wp_catalogs WHERE id ='".$id."'  and isValid='0'  "  ;
        $reslut = $this->wpdb->get_results($querystr);
        if(count($reslut)>0) {
            if ($upOrDown == 1) ///上移
                $querystr = "SELECT  * FROM wp_catalogs WHERE parentId ='" . $reslut[0]->parentId . "'  and isValid='0'and listOrder<'" . $reslut[0]->listOrder . "'  ORDER BY listOrder desc limit 0,1 ";
            else
                $querystr = "SELECT   * FROM wp_catalogs WHERE parentId ='" . $reslut[0]->parentId . "'  and isValid='0'and listOrder>'" . $reslut[0]->listOrder . "'  ORDER BY listOrder limit 0,1 ";
            //return $querystr;
            $changereslut = $this->wpdb->get_results($querystr);
            if(count($changereslut)>0) {
                $this->wpdb->query("update  `wp_catalogs` set listOrder='".$changereslut[0]->listOrder."' where id='".$id."' ");
                $this->wpdb->query("update  `wp_catalogs` set listOrder='".$reslut[0]->listOrder."' where id='".$changereslut[0]->id."' ");
                return 1;
            }
        }


        return 0;
    }



 /*
     *
     * 根据 id he  filename 修改天气路线
     *
     */
    public function changeDirType($id){

        return $this->wpdb->query("update  `wp_catalogs` set type=6-type where id='".$id."' ");
    }



    public function makeFile($filename){
        if ($handle = fopen($filename, 'w')) {
            fclose($handle);
            return true;
        }
        return false;
    }

    public function filemtime ($filename) {
        return @filemtime($filename);
    }

    public function copyFile ($from, $to) {
        return @copy($from, $to);
    }

    public function copyDir ($src, $dst) {
        $dir = opendir($src);
        $result = @mkdir($dst);
        while(false !== ( $file = readdir($dir)) ) {
            if (( $file != '.' ) && ( $file != '..' )) {
                if ( is_dir($src . '/' . $file) ) {
                    $this->copyDir($src . '/' . $file, $dst . '/' . $file);
                }
                else {
                    copy($src . '/' . $file,$dst . '/' . $file);
                }
            }
        }
        closedir($dir);
        return $result;
    }

    public function renameItem ($from, $to) {
        return @rename($from, $to);
    }

    public function readFile($filename){
        return file_get_contents($filename);
    }

    public function writefile($filename, $content){
        return @file_put_contents($filename, $content);
    }

    public function move_uploaded_file ($from, $to) {
        return @move_uploaded_file($from, $to);
    }

    public function parseImage($ext,$img,$file = null){
        $result = false;
        switch($ext){
            case 'png':
                $result = imagepng($img,($file != null ? $file : ''));
                break;
            case 'jpeg':
                $result = imagejpeg($img,($file ? $file : ''),90);
                break;
            case 'jpg':
                $result = imagejpeg($img,($file ? $file : ''),90);
                break;
            case 'gif':
                $result = imagegif($img,($file ? $file : ''));
                break;
        }
        return $result;
    }

    public function imagecreatefrompng($src) {
        return imagecreatefrompng($src);
    }

    public function imagecreatefromjpeg($src){
        return imagecreatefromjpeg($src);
    }

    public function imagecreatefromgif($src){
        return imagecreatefromgif($src);
    }
}

class GSFileManager {

    private $options;
    private $opt_param = 'opt';
    public static $root_param = 'rootDir';
    private $fileStorage;
    private $setUtf8Header = true;
    private $functions;
    private $itemNameRegex = '[/\?\*;:{}\\\\]+';

    private $destfile="";
    private $destpdf="";





    public function __construct($fileStorage, $options){
        $this->fileStorage = $fileStorage;
        $this->options = $options;
        $this->functions = array();
        $this->functions[1] = 'listDir';
        $this->functions[2] = 'makeFile';
        $this->functions[3] = 'makeDirectory';
        $this->functions[4] = 'deleteItem';
        $this->functions[5] = 'copyItem';
        $this->functions[6] = 'renameItem';
        $this->functions[7] = 'moveItems';
        $this->functions[8] = 'downloadItem';
        $this->functions[9] = 'readfile';
        $this->functions[10] = 'writefile';
        $this->functions[11] = 'uploadfile';
        $this->functions[12] = 'jCropImage';
        $this->functions[13] = 'imageResize';
        $this->functions[14] = 'copyAsFile';
        $this->functions[15] = 'serveImage';
        $this->functions[16] = 'zipItem';
        $this->functions[17] = 'unZipItem';




        $this->destfile=dirname(__FILE__) . '/../upfiles/';
        $this->destpdf=dirname(__FILE__) . '/../upfiles/pdf/';
    }

    public function getOptionValue ($key, $default = null) {
        $result = null;
        if (isset($this->options[$key])) {
            $result = $this->options[$key];
        } else if ($default === null) {
            $result = $default;
        }
        return $result;
    }

    public function getRequestFunction($index){
        $result = null;
        if (isset($this->functions[$index])) {
            $result = $this->functions[$index];
        }
        return $result;
    }


    /*
 *
 *根据不同的type 进行不同的操作
 *
 *
 */


    public function process($args){

        $actiontype=$args['opt'];

        /*
         *
         *$actiontype   ：
         *     1    显示目录
         *     2    新建文件夹
         *
         *     101 新建网址链接
         *     102  新建/更新 天气路线
         *
         *
         */


        ///读取目录
        if ($actiontype=='1') {
            return $this->listDir($args['dir']);


        }

        //新建目录
        else if ($actiontype=='3') {
            return $this->makeDirectory($args);


        }


        //新建/更新网址链接
        else if ($actiontype=='101') {
            return $this->newOrChangeLink($args);


        }
        //新建/更新 天气路线
        else if ($actiontype=='102') {
            return $this->newOrChangeWeatherPath($args);


        }


        //     显示/隐藏 某一文件或文件夹
        else if ($actiontype=='103') {
            return $this->fileStorage->changeDisplay($args['dir'],$args['display']);


        }

        //      修改某一条目位置
        else if ($actiontype=='104') {
            //

            return  $this->fileStorage->changeOrder($args['dir'],$args['upOrDown']);
        }


		 //     单显/正常 某一文件夹
        else if ($actiontype=='105') {
            //

            return  $this->fileStorage->changeDirType($args['dir']);
        }





        /////

        $responce = '';
        $functionName = $this->getRequestFunction($args[$this->opt_param]);

        if ($functionName != null) {
            $responce = $this->$functionName($args);
        } else {
            throw new Exception('ILlegalArgumentException: Uknown action '.$args[$this->opt_param], 6);

        }
        if ($this->setUtf8Header) {
            header ("Content-Type: text/html; charset=utf-8");
        }
        return $responce;
    }




    public function returnCorrectFunction($ext){
        $function = '';
        switch($ext){
            case 'png':
                $function = 'imagecreatefrompng';
                break;
            case 'jpeg':
                $function = 'imagecreatefromjpeg';
                break;
            case 'jpg':
                $function = 'imagecreatefromjpeg';
                break;
            case 'gif':
                $function = 'imagecreatefromgif';
                break;
        }
        return $function;
    }


    /*
     *
     * 处理上传文件
     *
     *
     */
    public function uploadfile($args) {


        $dir = $args['dir'];
        if (empty($_FILES)) {
            throw new Exception('ILlegalArgumentException: no files for upload', 11);
        }

        $maxSize = $this->getOptionValue('max_upload_filesize', 0);
        $responce = '{result: \'0\'}';
        foreach ($_FILES as $file) {


            $filename = trim($file['name']);

            //for windwow
            //$localfilename= iconv("UTF-8", "GB2312",$filename);
            // for linux
            $localfilename= iconv("UTF-8", "GBK",$filename);
            if (empty($filename)) {
                continue;
            }

            //return (dirname(__FILE__) . '/upfiles/'.$filename);
            $index=0;
            while(1)
            {
                $fullname='dir_'.$dir.'_'.$index.'_'.$localfilename;
                if (!$this->fileStorage->file_exists($this->destfile.$fullname)) {
                    if ($maxSize > 0 && $maxSize < intval($file['size']) / 1000) {
                        throw new Exception('ILlegalArgumentException: File to large '.$filename, 14);
                    }

                    if (($file["type"] != "application/pdf")&& ($file["type"] != "application/vnd.ms-powerpoint") && ($file["type"] != "application/msword")
                        && ($file["type"] != "application/vnd.ms-excel") && ($file["type"] != "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
                        && ($file["type"] != "application/vnd.openxmlformats-officedocument.presentationml.presentation"))
                    {
                        throw new Exception('ILlegalArgumentException: File type wrong '.$filename, 14);
                    }
                    $this->checkFileName($filename);

                    if ($this->fileStorage->move_uploaded_file($file['tmp_name'],$this->destfile.$fullname) === false){
                        /*  UPLOAD_ERR_OK
                               Value: 0; There is no error, the file uploaded with success.
                           UPLOAD_ERR_INI_SIZE
                               Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.
                           UPLOAD_ERR_FORM_SIZE
                               Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
                           UPLOAD_ERR_PARTIAL
                               Value: 3; The uploaded file was only partially uploaded.
                           UPLOAD_ERR_NO_FILE
                               Value: 4; No file was uploaded.
                           UPLOAD_ERR_NO_TMP_DIR
                               Value: 6; Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.
                           UPLOAD_ERR_CANT_WRITE
                               Value: 7; Failed to write file to disk. Introduced in PHP 5.1.0.
                           UPLOAD_ERR_EXTENSION
                               Value: 8; A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help. Introduced in PHP 5.2.0.
                          */
                        throw new Exception('ILlegalArgumentException: Can not upload File '.$filename.' reason: '.$file['error'], 16);
                    }

                    /// 将文件 转为为 pdf
                    $pdfname =md5($filename.time()).".pdf";
                    $cmd=dirname(__FILE__) . '/Office2Pdf.exe  '.$this->destfile.$fullname." ".$this->destpdf.$pdfname." ";
                    $needchange=true;


                    if ($file["type"] == "application/pdf")
                    {
                        copy($this->destfile.$fullname,$this->destpdf.$pdfname);
                    }
                    else {


                        $transfer=new  office2pdf();
                         $transfer->run($this->destfile.$fullname,$this->destpdf.$pdfname);
                    }

                    $this->fileStorage->add_uploaded_file($dir,$filename,'dir_'.$dir.'_'.$index.'_'.$filename,$pdfname);

                    break;

                } else {

                    $index++;

                }
                /*
                 *
                 * 需要更新时间
                 *
                 */
                //$this->fileStorage->add_uploaded_file($dir,$filename,$filename);
            }
        }

        $responce = '{result: \'1\'}';
        return $responce;
    }


    public function downloadItem($args) {

        if (isset($args['filename'])) {
            $filename = $args['filename'];
            $dir = $args['dir'];
            $dest = dirname(__FILE__) . '/../upfiles/';
            $result = $this->fileStorage->file_exists_1($dir);
            //for windwow
            //$localfilename= iconv("UTF-8", "GB2312",$filename);
            // for linux
            $localfilename= iconv("UTF-8", "GBK",$result[0]->fileAddr);
            if ($this->fileStorage->file_exists($dest.$localfilename)) {
                $content = $this->fileStorage->readFile($dest . $localfilename);
                header('Content-Description: Download File: ' . $filename);

                header('Content-Description: Download File: ' . $filename);
                header('Content-Type: application/octet-stream');
                header('Content-Disposition: attachment; filename="' . $filename . '"');
                header('Content-Transfer-Encoding: binary');
                header('Expires: 0');
                header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                header('Pragma: public');
                header('Content-Length: ' . strlen($content));
                echo $content;
                exit;
            } else {
                throw new Exception('ILlegalArgumentException: Source does NOT exists', 7);
            }
        }
        else {
            throw new Exception('ILlegalArgumentException: filename can NOT be null', 5);
        }
    }

    public function moveItems($args) {
        $root = $this->getOptionValue(self::$root_param);
        if (isset($args['files'])) {
            $files = explode(',,,', urldecode($args['files']));
            $dir = $args['dir'];
            $responce = '{result: \'0\'}';
            foreach ($files as $filename) {
                $filename = urldecode($filename);
                $filename = html_entity_decode($filename, ENT_QUOTES, 'UTF-8');
                $filename = $this->fixString($filename);
                if (strpos($filename, '..') !== false) {
                    throw new Exception('ILlegalArgumentException: dir can NOT go up', 13);
                }
                $this->checkFileName($filename);
                if ($this->fileStorage->file_exists($root.$filename)) {
                    if (!$this->fileStorage->file_exists($root.$dir.basename($filename))) {
                        if ($this->fileStorage->renameItem($root.$filename, $root.$dir.basename($filename))) {
                            $responce = '{result: \'1\'}';
                        }
                    } else {
                        throw new Exception('ILlegalArgumentException: Destination already exists '.$filename, 8);
                    }
                } else {
                    throw new Exception('ILlegalArgumentException: Source does NOT exists '.$filename, 7);
                }
            }
            return $responce;
        } else {
            throw new Exception('ILlegalArgumentException: files can NOT be null', 5);
        }
    }
    /*
     *
     *
     * 修改name
     *
     *
     *
     */
    public function renameItem($args) {
        $dir = $args['dir'];
        if (isset($args['newfilename'])) {
            $filename = $args['newfilename'];
            if (preg_match('#'.$this->itemNameRegex.'#', $filename) > 0){
                throw new Exception('ILlegalArgumentException: Invalid item name', 47);
            }
        } else {
            $filename = 'new name_'.time();
        }


        if ($this->fileStorage->renameItemName($dir,$filename)) {
            return '{result: \'1\'}';
        }
        return '{result: \'0\'}';
    }

    public function copyItem($args) {
        $root = $this->getOptionValue(self::$root_param);
        if (isset($args['files'])) {
            $files = explode(',,,', urldecode($args['files']));
            $dir = $args['dir'];
            $responce = '{result: \'0\'}';
            foreach ($files as $filename) {
                $filename = urldecode($filename);
                $filename = html_entity_decode($filename, ENT_QUOTES, 'UTF-8');
                $filename = $this->fixString($filename);
                if (strpos($filename, '..') !== false) {
                    throw new Exception('ILlegalArgumentException: dir can NOT go up', 13);
                }
                $this->checkFileName($filename);
                if ($this->fileStorage->file_exists($root.$filename)) {
                    if (!$this->fileStorage->file_exists($root.$dir.basename($filename))) {
                        if (!is_dir($root.$filename)) {
                            if ($this->fileStorage->copyFile($root.$filename, $root.$dir.basename($filename))) {
                                $responce = '{result: \'1\'}';
                            }
                        } else if ($this->fileStorage->copyDir($root.$filename, $root.$dir.basename($filename))){
                            $responce = '{result: \'1\'}';
                        }
                    } else {
                        throw new Exception('ILlegalArgumentException: Destination already exists '.$filename, 8);
                    }
                } else {
                    throw new Exception('ILlegalArgumentException: Source does NOT exists '.$filename, 7);
                }
            }
            return $responce;
        } else {
            throw new Exception('ILlegalArgumentException: filename can NOT be null', 5);
        }
    }



    /*
     * 删除 item
     *
     *
     *
     *
     */
    public function deleteItem($args) {
        $dir = $args['dir'];
        $result=$this->fileStorage->file_exists_1($dir);
        if(count($result)>0 ) {

            $file = $result[0];

            if ($file->type == '2') { ///是文件夹
                ////查看是否有子文件
                $files = $this->fileStorage->scandir($dir);
                if (count($files) > 0)
                    throw new Exception('文件夹非空： ' . $file->name, 3);
            }
            else if($file->type == '1') { ///是文件    需要删除 文件
                /*
                 *
                 * 删除文件
                 *
                 *
                 *
                 */
                $localfilename= iconv("UTF-8", "GBK",$file->fileAddr);
                $this->fileStorage->deleteFile($this->destfile.$localfilename);
                 $this->fileStorage->deleteFile($this->destpdf.$file->pdfAddr);



            }

            $this->fileStorage->deleteItem($dir);

            return '{result: \'1\'}';



        }
        else{
            throw new Exception('ILlegalArgumentException: dir to list does NOT exists '.$dir, 3);
        }
    }

    public function makeFile($args) {
        $root = $this->getOptionValue(self::$root_param);
        $dir = $args['dir'];
        if (isset($args['filename'])) {
            $filename = $args['filename'];
        } else {
            $filename = 'newfile_'.time().'.txt';
        }
        if (preg_match('#'.$this->itemNameRegex.'\.'.$this->itemNameRegex.'#', $filename) > 0){
            throw new Exception('ILlegalArgumentException: Invalid item name', 47);
        }
        if (!$this->fileStorage->file_exists($root.$dir.$filename)) {
            if ($this->fileStorage->makeFile($root.$dir.$filename)) {
                return '{result: \'1\'}';
            }
            return '{result: \'0\' , gserror: \'can not create item '.addslashes($dir.$filename).'\'}';
        } else {
            throw new Exception('ILlegalArgumentException: Destination already exists', 8);
        }
        return '{result: \'0\'}';
    }


    /*
     *
     * 新建文件夹
     *  参数
     *
     *
     */
    public function makeDirectory($args) {

        $dir = $args['dir'];
        if (isset($args['filename'])) {
            $filename = $args['filename'];
            if (preg_match('#'.$this->itemNameRegex.'#', $filename) > 0){
                throw new Exception('ILlegalArgumentException: Invalid item name', 47);
            }
        } else {
            $filename = 'new folder_'.time();
        }


        if ($this->fileStorage->filename_exists($dir,$filename) || $this->fileStorage->makeDirectory($dir,$filename)) {
            return '{result: \'1\'}';
        }
        return '{result: \'0\'}';
    }


    /*
     *
     * 新建/更新 网址链接
     * 参数
     *
     *
     */
    public function newOrChangeLink($args) {

        $id = $args['id'];
        $parentid = $args['parentid'];
        $name = $args['name'];
        $addr = $args['netAddr'];
        if($id==0)//新建
        {
            if ($this->fileStorage->filename_exists($parentid,$name) || $this->fileStorage->newLink($parentid,$name,$addr)) {
                return '{result: \'1\'}';
            }
        }
        else
        {
            $this->fileStorage->changeLink($id,$name,$addr);
            return '{result: \'1\'}';

        }

        return '{result: \'0\'}';
    }
    /*
     *
     * 新建/更新 天气路线
     * 参数
     *
     *
     */
    public function newOrChangeWeatherPath($args) {

        $id = $args['id'];
        $parentid = $args['parentid'];
        $source = $args['source'];
        $dest = $args['dest'];
        $name=$source."--".$dest;
        if($id==0)//新建
        {
            if ($this->fileStorage->filename_exists($parentid,$name) || $this->fileStorage->newWeatherPath($parentid,$source,$dest)) {
                return '{result: \'1\'}';
            }
        }
        else
        {
            if ( $this->fileStorage->changeWeatherPath($id,$source,$dest)) {
                return '{result: \'1\'}';
            }
        }

        return '{result: \'0\'}';
    }


    /*
     *
     * ////根据id 查询数据库中所有父目录为该id的文件或文件夹
     *
     *
     *
     *
     *
     */
    public function listDir($args) {

        $id = $args;
        $result=$this->fileStorage->file_exists_1($id);
        if(count($result)>0 ) {

            ///获取 目录路径
            $path="/";
            while(count($result) > 0 && $result[0]->id != "1")
            {

                $path="/".$result[0]->name.$path;
                $result=$this->fileStorage->file_exists_1($result[0]->parentId);

            }
            $html = 'var path="'.$path.'"; ';

            $html .= 'var type="'.$result[0]->type.'"; ';
            $html .= 'var gsdirs = new Array();';
            $html .= 'var gsfiles = new Array();';
            $dirs = array();
            $files = $this->fileStorage->scandir($id);

            if( count($files) > 0 ) {
                foreach( $files as $file ) {

                    /*
                     * type 类型  2 文件夹   1  文件 0 网址
                     */


                    if( $file->type == '1') { ///是文件
                        ///// 自身文件名  绝对路径 是否显示  id  文件类型名  时间
                        $html .= 'gsfiles.push(new gsItem("1", "'.htmlentities($file->name, ENT_QUOTES, 'UTF-8').'", "'.htmlentities($file->pathName, ENT_QUOTES, 'UTF-8').'","'.htmlentities($file->display, ENT_QUOTES, 'UTF-8').'","'.htmlentities($file->id, ENT_QUOTES, 'UTF-8').'", "文件", "'.htmlentities($file->createTime, ENT_QUOTES, 'UTF-8').'"));';
                    } else if( $file->type== '2'){  ///是文件夹
                        $html .= 'gsdirs.push(new gsItem("2", "'.htmlentities($file->name, ENT_QUOTES, 'UTF-8').'", "'.htmlentities($file->pathName, ENT_QUOTES, 'UTF-8').'","'.htmlentities($file->display, ENT_QUOTES, 'UTF-8').'", "'.htmlentities($file->id, ENT_QUOTES, 'UTF-8').'", "累计文件夹","'.htmlentities($file->createTime, ENT_QUOTES, 'UTF-8').'"));';
                        $html .= 'gsfiles.push(new gsItem("2", "'.htmlentities($file->name, ENT_QUOTES, 'UTF-8').'", "'.htmlentities($file->pathName, ENT_QUOTES, 'UTF-8').'","'.htmlentities($file->display, ENT_QUOTES, 'UTF-8').'", "'.htmlentities($file->id, ENT_QUOTES, 'UTF-8').'", "累计文件夹","'.htmlentities($file->createTime, ENT_QUOTES, 'UTF-8').'"));';

                    }
					 else if( $file->type== '4'){  ///单线文件夹
                        $html .= 'gsdirs.push(new gsItem("2", "'.htmlentities($file->name, ENT_QUOTES, 'UTF-8').'", "'.htmlentities($file->pathName, ENT_QUOTES, 'UTF-8').'","'.htmlentities($file->display, ENT_QUOTES, 'UTF-8').'", "'.htmlentities($file->id, ENT_QUOTES, 'UTF-8').'", "迭代文件夹","'.htmlentities($file->createTime, ENT_QUOTES, 'UTF-8').'"));';
                        $html .= 'gsfiles.push(new gsItem("2", "'.htmlentities($file->name, ENT_QUOTES, 'UTF-8').'", "'.htmlentities($file->pathName, ENT_QUOTES, 'UTF-8').'","'.htmlentities($file->display, ENT_QUOTES, 'UTF-8').'", "'.htmlentities($file->id, ENT_QUOTES, 'UTF-8').'", "迭代文件夹","'.htmlentities($file->createTime, ENT_QUOTES, 'UTF-8').'"));';

                    }

                    else if( $file->type== '0'){  ///是网址
                        $html .= 'gsfiles.push(new gsItem("0", "'.htmlentities($file->name, ENT_QUOTES, 'UTF-8').'", "'.htmlentities($file->pathName, ENT_QUOTES, 'UTF-8').'","'.htmlentities($file->display, ENT_QUOTES, 'UTF-8').'","'.htmlentities($file->id, ENT_QUOTES, 'UTF-8').'", "网址链接","'.htmlentities($file->createTime, ENT_QUOTES, 'UTF-8').'"));';
                    }
                    else if( $file->type== '3'){  ///是 天气路线
                        $html .= 'gsfiles.push(new gsItem("3", "'.htmlentities($file->name, ENT_QUOTES, 'UTF-8').'", "'.htmlentities($file->pathName, ENT_QUOTES, 'UTF-8').'","'.htmlentities($file->display, ENT_QUOTES, 'UTF-8').'","'.htmlentities($file->id, ENT_QUOTES, 'UTF-8').'", "航班路线","'.htmlentities($file->createTime, ENT_QUOTES, 'UTF-8').'"));';
                    }
                }


            }
            return $html;
        } else {
            throw new Exception('ILlegalArgumentException: dir to list does NOT exists '.$id, 3);
        }
    }

    public function checkFileName($filename){
        if ($filename == '.htaccess') {
            throw new Exception('ILlegalArgumentException: Source does NOT exists '.$filename, 7);
        }
    }

    function fixString($String){
        if (get_magic_quotes_gpc() or get_magic_quotes_runtime()) {
            return stripcslashes($String);
        }
        return $String;
    }
}




set_time_limit(0);
error_reporting(E_ALL);
ini_set('display_errors', true);
mb_internal_encoding("UTF-8");

$options = array();
$options['max_upload_filesize'] = '-1'; //(the size in Kbytes)
$manager = new GSFileManager(new GSFileSystemFileStorage($wpdb), $options);
try {

    $result =$manager->process($_REQUEST);

} catch (Exception $e) {
    $result = '{result: \'0\', gserror: \''.addslashes($e->getMessage()).'\', code: \''.$e->getCode().'\'}';
}
echo $result;








?>